import React from 'react';
import { Form, Radio, DatePicker, TreeSelect, Spin, Select } from 'antd';
import { router, withRouter } from 'umi';
import moment from 'moment';
import { useRequest, defaultFormatResult } from '@/hooks';
import { Company } from '@/containers';
import { getEmailList } from '../../service';
import { getChannelTreeWithoutTalent } from '../../../Setting/service';

const { Option } = Select;

const filterTree = (tree = []) =>
    tree.map(({ childrenChannelValues, channelName, channelCode, ...props }) => ({
        children: childrenChannelValues && childrenChannelValues.length > 0 ? filterTree(childrenChannelValues) : '',
        title: channelName,
        value: channelName === '外部渠道' ? '0' : channelCode,
        ...props
    }));

const HistoryTotalForm = ({ form, location, type, onChange }) => {
    const { query = {} } = location;
    const { getFieldDecorator } = form;
    // console.log('HistoryTotalForm -> query', query);
    const [visible, setVisible] = React.useState(false);

    const { data: channelTree, loading: channelLoading, run: fetchChannelTree } = useRequest(
        () => getChannelTreeWithoutTalent({ channelStatus: 1 }),
        {
            manual: true,
            ...defaultFormatResult
        }
    );

    const { data: emailList, loading: emailLoading, run: fetchEmailList } = useRequest(getEmailList, {
        manual: true,
        ...defaultFormatResult
    });

    const handleSubmit = () => {
        const params = form.getFieldsValue();
        const { rangeTime = [], ...rest } = params;
        const finalParams = {
            ...rest,
            operateStartDate: rangeTime.length > 0 ? rangeTime[0]?.format('YYYY-MM-DD') : '',
            operateEndDate: rangeTime.length > 1 ? rangeTime[1]?.format('YYYY-MM-DD') : ''
        };
        history.push({ query: { ...query, ...finalParams, pageNo: 1 } });
        if (onChange) {
            onChange(finalParams);
        }
    };

    const getDefaultRangeTime = () => [moment().subtract(6, 'days'), moment()];

    const handleQuickDate = e => {
        if (!e.target.value) {
            return;
        }
        const arr = e.target.value.split(',');
        const start = arr[0];
        const duration = arr[1];
        const operateStartDate = moment().subtract(Number(start) + Number(duration) - 1, 'days');
        const operateEndDate = moment().subtract(Number(start), 'days');
        form.setFieldsValue({
            dateQuick: e.target.value,
            rangeTime: [operateStartDate, operateEndDate]
        });
        handleSubmit();
    };

    const handleDateChange = date => {
        form.setFieldsValue({
            dateQuick: undefined,
            rangeTime: date
        });
        handleSubmit();
    };

    const handleChannelChange = e => {
        form.setFieldsValue({
            channelType: e.target.value,
            channelCodes: undefined
        });
        if (e.target.value !== '3') {
            handleSubmit();
        }
    };

    const handleTypeChange = e => {
        form.setFieldsValue({
            operateType: e.target.value
        });
        handleSubmit();
    };

    const handleVisibleChange = v => {
        setVisible(v);
        if (!v) {
            handleSubmit();
        }
    };

    const handleSelectChange = v => {
        form.setFieldsValue({
            channelCodes: v
        });
        if (!visible) {
            handleSubmit();
        }
    };

    const handleCompanyChange = e => {
        form.setFieldsValue({
            companyCode: e,
            fetchMails: undefined
        });
        fetchEmailList({ organizationCode: e });
        handleSubmit();
    };

    const handleEmailChange = e => {
        form.setFieldsValue({
            fetchMails: e
        });
        if (!visible) {
            handleSubmit();
        }
    };

    React.useEffect(() => {
        if (type === 'publish' || type === 'resume') {
            fetchChannelTree(query?.channelCompanyCode ? { channelCompanyCode: query?.channelCompanyCode } : {});
        } else if (type === 'email') {
            fetchEmailList({ organizationCode: query?.companyCode || '' });
        }
    }, []);

    return (
        <Form layout="inline">
            <Form.Item label="时间" style={{ display: 'block' }}>
                {getFieldDecorator('dateQuick', {
                    initialValue: query?.operateStartDate ? query?.dateQuick : query?.dateQuick || '0,7'
                })(
                    <Radio.Group onChange={handleQuickDate} style={{ marginRight: 12 }}>
                        <Radio.Button value="0,1">今天</Radio.Button>
                        <Radio.Button value="1,1">昨天</Radio.Button>
                        <Radio.Button value="0,7">近七天</Radio.Button>
                        <Radio.Button value="0,30">近30天</Radio.Button>
                    </Radio.Group>
                )}
                {getFieldDecorator('rangeTime', {
                    initialValue:
                        (query?.operateStartDate &&
                            query?.operateEndDate && [
                                moment(query?.operateStartDate),
                                moment(query?.operateEndDate)
                            ]) ||
                        getDefaultRangeTime()
                })(<DatePicker.RangePicker allowClear={false} style={{ width: 250 }} onChange={handleDateChange} />)}
            </Form.Item>
            {(type === 'publish' || type === 'resume') && (
                <Form.Item label="渠道">
                    <div style={{ display: 'flex', flexWrap: 'wrap' }}>
                        {getFieldDecorator('channelType', {
                            initialValue: query?.channelType || '0'
                        })(
                            <Radio.Group onChange={handleChannelChange} style={{ marginRight: 12, paddingTop: 4 }}>
                                <Radio.Button value="0">全部</Radio.Button>
                                <Radio.Button value="1">内部</Radio.Button>
                                <Radio.Button value="2">外部</Radio.Button>
                                <Radio.Button value="3">自定义</Radio.Button>
                            </Radio.Group>
                        )}
                        {form.getFieldValue('channelType') === '3' && (
                            <Spin spinning={channelLoading}>
                                {getFieldDecorator('channelCodes', {
                                    initialValue: query?.channelCodes || undefined
                                })(
                                    <TreeSelect
                                        showSearch
                                        multiple
                                        style={{ width: 265 }}
                                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                        treeData={filterTree(channelTree || [])}
                                        placeholder="请选择"
                                        treeDefaultExpandAll
                                        getPopupContainer={trigger => trigger.parentElement}
                                        treeCheckable
                                        treeNodeFilterProp="title"
                                        maxTagCount={2}
                                        onDropdownVisibleChange={handleVisibleChange}
                                        onChange={handleSelectChange}
                                    />
                                )}
                            </Spin>
                        )}
                    </div>
                </Form.Item>
            )}
            {type === 'publish' && (
                <Form.Item label="类型">
                    {getFieldDecorator('operateType', {
                        initialValue: query?.operateType || '1'
                    })(
                        <Radio.Group onChange={handleTypeChange}>
                            <Radio.Button value="0">全部</Radio.Button>
                            <Radio.Button value="1">发布</Radio.Button>
                            <Radio.Button value="2">更新</Radio.Button>
                            <Radio.Button value="3">上线</Radio.Button>
                            <Radio.Button value="4">下线</Radio.Button>
                        </Radio.Group>
                    )}
                </Form.Item>
            )}
            {type === 'email' && (
                <>
                    <Form.Item label="行政机构">
                        {getFieldDecorator('companyCode', {
                            initialValue: query?.companyCode || undefined
                        })(
                            <Company
                                style={{ width: 148 }}
                                placeholder="请选择行政机构"
                                onChange={handleCompanyChange}
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="邮箱">
                        <Spin spinning={emailLoading}>
                            {getFieldDecorator('fetchMails', {
                                initialValue: query?.fetchMails || undefined
                            })(
                                <Select
                                    mode="multiple"
                                    maxTagCount={1}
                                    allowClear
                                    style={{ width: 266 }}
                                    placeholder="请选择邮箱"
                                    onDropdownVisibleChange={handleVisibleChange}
                                    onChange={handleEmailChange}
                                >
                                    {emailList?.map(item => (
                                        <Option key={item.email} value={item.email} label={item.email}>
                                            {item.email}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                </>
            )}
        </Form>
    );
};

export default withRouter(Form.create({})(HistoryTotalForm));
